<template>
    <div v-if="showPage" class="pa12" style="min-width: 1000px;">
        <el-card class="bg-none">
            <ul class="f-d-b fz12">
                <li class="flex"><span class="text-nowrap">优惠券名称：</span><span>{{ detail.name }}</span></li>
                <li class="flex"><span class="text-nowrap">适用范围：</span><span>{{ couponChannelText[detail.channel] }}</span></li>
                <li class="flex"><span class="text-nowrap">优惠券类型：</span><span>{{ couponTypesLabel[detail.soule] }}</span></li>
                <li v-if="detail.purpose === 2" class="flex">
                    <span class="text-nowrap">关联游戏：</span><span>{{ detail.link ? detail.link.name : '--' }}</span>
                </li>
                <li class="flex"><span class="text-nowrap">优惠券用途：</span><span>{{ couponPurposeLabel[detail.purpose] }}</span></li>
                <li class="flex"><span class="text-nowrap">有效期：</span><span>{{ detail.validPeriodText }}</span></li>
            </ul>
        </el-card>

        <div class="flex pt13">
            <el-card class="bg-none flex1">
                <template #header><span class="fz14">领用数据统计</span></template>
                <ul class="flex fz12">
                    <li class="flex1">
                        <span class="pr13">领取率</span>
                        <span class="fz24 detail-stats__rate" style="color: #4CC9AE;">{{ detail.receiveRate }}%</span>
                    </li>
                    <li class="flex1">
                        <span class="pr13">核销率</span>
                        <span class="fz24 detail-stats__rate" style="color: #FBBA5B;">{{ detail.verifyRate }}%</span>
                    </li>
                    <li v-if="baoLiCustom" class="flex1">
                        <span class="pr13">结算率</span>
                        <span class="fz24 detail-stats__rate" style="color: #F57383;">{{ detail.settlementRate }}%</span>
                    </li>
                </ul>
                <div ref="chartBarStats" style="width: 100%;height: 240px;"/>
            </el-card>

            <el-card v-if="baoLiCustom && +routeParams.origin === 1" class="bg-none ml12 flex1" :body-style="{ padding: 0 }">
                <template #header><span class="fz14">店铺核销统计</span></template>
                <el-table
                    v-loading="tableVerifyLoading"
                    :data="tableDataVerify"
                    :empty-text="emptyTextVerify"
                    @sort-change="tableVerifySortChange"
                    height="305"
                    class="table-loading-mask-body model-table-border-none"
                >
                    <el-table-column label="店铺ID" min-width="90">
                        <template #default="{ row }">{{ row.shop_id || '--' }}</template>
                    </el-table-column>
                    <el-table-column label="店铺名称" min-width="170" show-overflow-tooltip>
                        <template #default="{ row }">{{ row.shop_name || '--' }}</template>
                    </el-table-column>
                    <el-table-column label="核销数量" min-width="90" sortable="custom">
                        <template #default="{ row }">
                            <span v-if="row.verify_num || row.verify_num === 0">{{ row.verify_num }}</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="核销占比" min-width="90" sortable="custom">
                        <template #default="{ row }">
                            <span v-if="row.verify_rate">{{ row.verify_rate }}</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <el-card class="bg-none ml12 flex1">
                <template #header><span class="fz14">领用数据趋势</span></template>
                <div ref="chartLineRecord" style="width: 100%;height: 270px;"/>
            </el-card>
        </div>

        <el-card class="bg-none mt12" :body-style="{ padding: 0 }">
            <template #header>
                <ul class="f-c-b">
                    <li class="fz14 text-nowrap">领用数据明细（{{ total }}）</li>
                    <li class="f-c">
                        <GFilterTime type="couponReport" :value="params" @change="mdSearch"/>
                        <el-input
                            v-model="params.keyword"
                            @keyup.enter="mdTableSearch"
                            @clear="mdTableSearch"
                            placeholder="输入会员名称、手机号搜索"
                            class="w200 mh12"
                            clearable
                        >
                            <template #suffix>
                                <el-icon @click="mdTableSearch" class="pointer">
                                    <Search/>
                                </el-icon>
                            </template>
                        </el-input>
                        <el-button type="primary" :loading="baoLiCustomExportLoading" :disabled="baoLiCustomExportLoading" @click="showExportModel">
                            <el-icon class="mb1">
                                <Download/>
                            </el-icon>
                            &nbsp;导出领用明细
                        </el-button>
                        <el-button type="primary" @click="showSettleExportModel">
                            <el-icon class="mb1">
                                <Download/>
                            </el-icon>
                            &nbsp;导出结算率
                        </el-button>
                    </li>
                </ul>
            </template>

            <el-table
                v-loading="tableLoading"
                :data="tableData"
                :empty-text="emptyText"
                @sort-change="tableSortChange"
                class="table-loading-mask-body"
            >
                <el-table-column label="优惠券券号" min-width="135">
                    <template #default="{ row }">{{ row.source || '--' }}</template>
                </el-table-column>
                <el-table-column :label="isScanCodeSendCoupon ? '领取人微信名' : '会员昵称'" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">{{ row.member_name || '--' }}</template>
                </el-table-column>
                <el-table-column :label="isScanCodeSendCoupon ? '领取人手机号' : '会员手机号'" min-width="120">
                    <template #default="{ row }">{{ row.member_phone || '--' }}</template>
                </el-table-column>
                <el-table-column label="领取时间" property="created_at" min-width="160" sortable="custom">
                    <template #default="{ row }">{{ row.created_at || '--' }}</template>
                </el-table-column>
                <el-table-column v-if="isScanCodeSendCoupon" min-width="100">
                    <template #header>
                        <GTableHeadSelect
                            name="领取方式"
                            :filters="receiveFilters"
                            v-model="params.origin"
                            @change="mdTableSearch"
                        />
                    </template>
                    <template #default="{ row }">{{ row.origin || '--' }}</template>
                </el-table-column>
                <el-table-column v-if="isScanCodeSendCoupon" label="发券店铺" min-width="160" show-overflow-tooltip>
                    <template #default="{ row }">{{ row.sended_in || '--' }}</template>
                </el-table-column>
                <el-table-column v-if="isScanCodeSendCoupon" label="发券人" min-width="120" show-overflow-tooltip>
                    <template #default="{ row }">{{ row.sended_by || '--' }}</template>
                </el-table-column>
                <el-table-column min-width="100">
                    <template #header>
                        <GTableHeadSelect
                            name="使用状态"
                            :filters="statusFilters"
                            v-model="params.status"
                            @change="mdTableSearchStatus"
                        />
                    </template>
                    <template #default="{ row }">{{ statusFiltersLabel[row.status] || '--' }}</template>
                </el-table-column>
                <el-table-column label="使用店铺" min-width="160" show-overflow-tooltip>
                    <template v-if="baoLiCustom" #header>
                        <GTableHeadSelect
                            name="使用店铺"
                            :props="{ value: 'id', label: 'name' }"
                            :filters="shopFilters"
                            v-model="params.shop_id"
                            @change="mdTableSearch"
                        />
                    </template>
                    <template #default="{ row }">{{ row.shop_name || '--' }}</template>
                </el-table-column>
                <el-table-column label="使用场景" min-width="100">
                    <template #default="{ row }">{{ couponChannelText[row.channel] || '--' }}</template>
                </el-table-column>
                <el-table-column label="使用时间" property="verified_at" min-width="160" sortable="custom">
                    <template #default="{ row }">{{ row.verified_at || '--' }}</template>
                </el-table-column>
                <el-table-column v-if="baoLiCustom" min-width="100">
                    <template #header>
                        <GTableHeadSelect
                            name="结算状态"
                            :filters="settlementFilters"
                            v-model="params.settlement_status"
                            @change="mdTableSearchStatus"
                        />
                    </template>
                    <template #default="{ row }">
                        <div v-if="(row.settlement_status === 0 && row.status === 1) || row.settlement_status === 1">
                            {{ settlementFiltersLabel[row.settlement_status] || '--' }}
                        </div>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column v-if="baoLiCustom && showSettlementBtn" fixed="right" width="120">
                    <template #header><span class="pl3">操作</span></template>
                    <template #default="{ row }">
                        <div v-if="row.settlement_status === 1 || (row.status === 1 && row.settlement_status === 0)">
                            <el-button v-if="row.settlement_status === 0" link type="primary" @click="showSettlementDialog(row)">结算</el-button>
                            <el-button v-if="row.settlement_status === 1" link type="primary" @click="showSettlementDialog(row)">取消结算</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <div class="f-d-c pv20">
                <GPagination
                    :current-page="params.page"
                    :page-size="params.per_page"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>
    </div>

    <!--切换 结算/不结算-->
    <el-dialog v-model="settlementDialog" :close-on-click-modal="false" title="提示信息" width="280px">
        <div class="text-c pt10 pb15">确认{{ tableDataRow.settlement_status === 1 ? '取消' : '' }}结算吗？</div>
        <template #footer>
            <el-button @click="cancelSettlementDialog">取消</el-button>
            <el-button @click="changeSettlement" type="primary" :loading="settlementLoading" :disabled="settlementLoading">确认</el-button>
        </template>
    </el-dialog>

    <!--导出结算-->
    <el-dialog v-model="exportSettlementDialog" :close-on-click-modal="false" title="提示信息" width="330px">
        <div class="text-c pt10 pb15">
            <div class="pb8">当前导出数据含"未结算"数据</div>
            <div>导出时是否结算?</div>
        </div>
        <template #footer>
            <el-button @click="noSettlement">不结算</el-button>
            <el-button type="primary" @click="onSettlement">结算</el-button>
        </template>
    </el-dialog>

    <!--导出-->
    <GExportModel
        ref="ExportModelRef"
        v-model="exportDialogVisible"
        :config="exportConfig"
        @close-router="updateDetail"
    />
</template>

<script setup lang="ts">
    import { reactive, ref, onMounted, nextTick, onUnmounted, computed } from "vue";
    import * as echarts from "echarts";
    import { useRoute, useRouter } from "vue-router";
    import { Search, Download } from "@element-plus/icons-vue";
    import { ElMessage } from "element-plus";
    import useLoading from "@/hooks/loading";
    import {
        getApiSystemElement,
        getRestfulMallCouponRecord,
        getRestfulMallCouponRecordDetail,
        getRestfulMallCouponShops,
        postV3CouponVerifyStatsByShop,
        postV3MemberCouponSettlement,
    } from "@/assets/api";
    import { getRestfulMallV2CouponDetailHandler } from "@/assets/api/handler";
    import { getFiltersDictLabel } from "@/filters/utils";
    import { CouponPurpose } from "@/filters/data";
    import { FCouponTypesLabel, FCouponChannelText } from "@/filters";
    import { TypeFilters } from "@/interface/filters";
    import { isBaoLiCustom } from "@/utils/customMall";
    import { getTableSortOrder, TypeSortParams, TypeTableSort } from "@/utils/handlerData";
    import { FilterTimesRow } from "@/components/globalUtils/GFilterTime";
    import { TypeExport } from "@/interface/export";
    import { _layoutStore, _mallStore } from "@/store/config";

    const { showLoading, hideLoading } = useLoading();// 加载loading
    const route = useRoute();
    const router = useRouter();
    const baoLiCustom = ref<boolean>(isBaoLiCustom());

    const couponPurposeLabel = reactive<ObjValueStr>(getFiltersDictLabel(CouponPurpose()));
    const couponTypesLabel = reactive<ObjValueStr>(FCouponTypesLabel);// 类型
    const couponChannelText = reactive<ObjValueStr>(FCouponChannelText);// 适用范围

    let isChartThemeFontColor: string = '';
    let isChartThemeLineColor: string = '#dddddd';
    const getChardThemeDark = () => {
        isChartThemeFontColor = _layoutStore.isThemeDark ? '#FFFFFF' : '#303133';
    }
    getChardThemeDark();
    _layoutStore.$subscribe((mutate: ObjValueAny) => {
        if (mutate.events.key === 'isThemeDark') {
            getChardThemeDark();
            getChartStats();
            getChardCouponRecord();
        }
    })

    // 扫码发券
    const isScanCodeSendCoupon = computed(() => {
        return detail.value.purpose === 7;
    })

    let showPage = ref<boolean>(false);
    onMounted(() => {
        showLoading();
        showPage.value = false;
        initPromise();
        getMallCouponShops();
        getCouponRecordDetail();
        if (baoLiCustom.value) {
            params.shop_id = '';
            params.settlement_status = '';
            getSystemElement();
            getVerifyStatsByShop();
        }
    })

    const showSettlementBtn = ref<boolean>(false);// 显示 结算/取消结算 按钮
    const getSystemElement = () => {
        const params = {
            company_id: _mallStore.companyId,
            mall_id: _mallStore.mallId,
            system: 5,
            id: 407,
        }
        getApiSystemElement(params).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                showSettlementBtn.value = resp.data.includes('优惠券结算');
            } else {
                ElMessage.error(resp.msg);
            }
        })
    }

    onUnmounted(() => {
        window.onresize = null;
    })

    const routeParams: ObjValueAny = reactive<ObjValueAny>(route.params);// url参数

    const initPromise = () => {
        Promise.all([
            getRestfulMallV2CouponDetailHandler(+routeParams.id),// 优惠券详情
            getRestfulMallCouponRecord(+routeParams.id),// 领用数据趋势
        ]).then((resp: ObjValueAny[]) => {
            showPage.value = true;
            getDetail(resp[0]);
            getMallCouponRecord(resp[1]);
            nextTick(() => {
                window.onresize = () => {
                    // 让图表的宽度和高度自适应其父容器的宽度和高度
                    (chartInstanceStats as echarts.ECharts).resize();
                    (chartInstanceRecord as echarts.ECharts).resize();
                };
            })
            hideLoading();
        })
    }
    // 优惠券详情
    let detail = ref<ObjValueAny>({});
    const getDetail = (resp: ObjValueAny) => {
        if (resp.code === 200) {
            detail.value = resp.data;
            getStats();
            nextTick(() => {
                if (chartInstanceStats) {
                    chartInstanceStats.dispose();
                }
                getChartStats();
            });
        } else {
            ElMessage.error(`getRestfulMallV2CouponDetail：${resp.msg}`);
        }
    }
    // 领用数据统计
    const getStats = () => {
        const couponNum: number = +detail.value.purpose === 5 ? +detail.value.published_num : +detail.value.num;
        const verifyNum: number = (+detail.value.online_verify_num || 0) + (+detail.value.verify_num || 0);
        // 核销率
        if (+detail.value.receive_num > 0) {
            detail.value.verifyRate = parseInt((verifyNum / (+detail.value.receive_num) * 100).toString());
        } else {
            detail.value.verifyRate = 0;
        }
        // 领取率
        if (couponNum > 0) {
            detail.value.receiveRate = parseInt(((+detail.value.receive_num || 0) / couponNum * 100).toString());
        } else {
            detail.value.receiveRate = 0;
        }
        // 结算率
        if (verifyNum > 0) {
            detail.value.settlementRate = parseInt(((+detail.value.settlement_num || 0) / verifyNum * 100).toString());
        } else {
            detail.value.settlementRate = 0;
        }
    }

    // 领用数据统计 统计图
    const chartBarStats = ref<HTMLElement | null>(null);
    let chartInstanceStats: echarts.ECharts | null = null;
    const getChartStats = () => {
        const colors: string[] = ['#FF8186', '#A963FF', '#FFB743', '#0DFDF2', '#027DFF', '#FFFE92'];
        const yData: string[] = ['线上使用', '线下核销', '已领取', '已发放', '优惠券总量'];
        const seriesData: number[] = [detail.value.online_verify_num, detail.value.verify_num, detail.value.receive_num];
        if (detail.value.purpose === 5) {
            seriesData.push(detail.value.published_num);
        } else {
            seriesData.push(detail.value.num);
        }
        seriesData.push(detail.value.num);
        if (baoLiCustom.value) {
            yData.unshift('已结算');
            seriesData.unshift(detail.value.settlement_num || 0);
        }
        if (chartBarStats.value) {
            if (!chartInstanceStats) {
                chartInstanceStats = echarts.init(chartBarStats.value);
            }
            chartInstanceStats.setOption({
                grid: {
                    left: 0,
                    right: 80,
                    top: 20,
                    bottom: -10,
                    containLabel: true
                },
                xAxis: {
                    show: false,
                },
                yAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: false
                    },
                    axisLabel: {
                        show: true,
                        color: isChartThemeFontColor,
                        fontSize: 13
                    },
                    data: yData
                },
                series: [
                    {
                        type: 'bar',
                        barWidth: '25',
                        label: {
                            show: true,
                            position: 'right',
                            color: isChartThemeFontColor,
                            fontSize: 13,
                            formatter: '{c}' + '张',
                        },
                        itemStyle: {
                            borderRadius: 5,
                            color: (data: ObjValueAny) => {
                                return colors[data.dataIndex];
                            }
                        },
                        emphasis: {
                            label: {
                                fontSize: 14,
                                fontWeight: 'bold'
                            }
                        },
                        data: seriesData
                    },
                ]
            });
        }
    }

    // 领用数据趋势
    let records = ref<ObjValueAny[]>([]);
    const weekDayArray: string[] = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const chartLineRecord = ref<HTMLElement | null>(null);
    let chartInstanceRecord: echarts.ECharts | null = null;
    const getMallCouponRecord = (resp: ObjValueAny) => {
        if (resp.code === 200) {
            records.value = resp.data;
            nextTick(() => {
                if (chartInstanceRecord) {
                    chartInstanceRecord.dispose();
                }
                getChardCouponRecord();
            });
        } else {
            ElMessage.error(resp.msg);
        }
    }
    const getChardCouponRecord = () => {
        const optionData: ObjValueAny = {
            times: [],
            series: [
                { title: '领取优惠券', data: [], color: '#FBBA5B' },
                { title: '核销优惠券', data: [], color: '#0DFDF2' },
            ],
        }
        for (let row of records.value) {
            optionData.times.push(row.date);
            optionData.series[0].data.push(row.receive_num || 0);
            optionData.series[1].data.push(row.verify_num || 0);
        }
        if (chartLineRecord.value) {
            if (!chartInstanceRecord) {
                chartInstanceRecord = echarts.init(chartLineRecord.value);
            }
            const option: ObjValueAny = {
                tooltip: {
                    trigger: 'axis',
                    // 自定义函数修改折线图给数据加单位
                    formatter: (data: ObjValueAny[]) => {
                        const weekDay: number = new Date(data[0].name).getDay();
                        let str: string = '';
                        str = `<div class="f-c-b"><span class="pl3">${data[0].name}</span><span>${weekDayArray[weekDay]}</span></div>`;// 显示日期
                        for (let i = 0; i < data.length; i++) {
                            str += `
                                <div class="f-c pt6" style="width: fit-content;">
                                    <span class="chart-tooltip-formatter__circle--dot" style="background-color: ${data[i].color};"></span>
                                    <span class="w90 pl6">${data[i].seriesName}</span>
                                    <span class="fwbold pr2">${data[i].data}</span>张
                                </div>
                            `;
                        }
                        return str;
                    },
                    axisPointer: {
                        type: 'line',
                        lineStyle: {
                            z: 1,
                            width: 2,
                            color: isChartThemeLineColor
                        }
                    },
                },
                grid: {
                    left: 10,
                    right: 20,
                    top: 20,
                    bottom: 30,
                    containLabel: true
                },
                legend: {
                    right: 10,
                    bottom: 0,
                    itemGap: 8,
                    itemWidth: 8,
                    itemHeight: 8,
                    textStyle: {
                        color: isChartThemeFontColor
                    },
                    data: [],
                    selectedMode: false
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: isChartThemeLineColor
                        }
                    },
                    boundaryGap: false,
                    data: optionData.times,
                    axisLabel: {
                        color: isChartThemeFontColor,
                        fontSize: 12,
                        fontWeight: 400,
                        margin: 10,
                        formatter: (data: string) => {
                            return data.substring(5, 10);
                        }
                    },
                },
                yAxis: {
                    minInterval: 1,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: isChartThemeLineColor
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: isChartThemeLineColor
                        }
                    },
                    axisLabel: {
                        color: isChartThemeFontColor,
                    }
                },
                series: []
            }
            for (let i = 0; i < optionData.series.length; i++) {
                const row: ObjValueAny = optionData.series[i];
                option.legend.data.push({
                    name: row.title,
                    icon: 'circle'
                });
                option.series[i] = {
                    name: row.title,
                    type: 'line',
                    //曲线的颜色
                    lineStyle: {
                        color: row.color,
                        width: 2
                    },
                    symbolSize: 5,
                    //折线拐点标志的样式
                    itemStyle: {
                        color: row.color,
                        borderWidth: 2
                    },
                    data: row.data,
                    z: 100,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0.2,
                            x2: 0,
                            y2: 1,
                            colorStops: [
                                {
                                    offset: 0.2,
                                    color: row.color // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: row.color // 100% 处的颜色
                                }
                            ]
                        },
                        opacity: 0.1
                    }
                };
            }
            chartInstanceRecord.setOption(option);
        }
    }

    // 店铺核销统计 ==================================================================================================
    let tableDataVerify = ref<ObjValueAny[]>([]);
    let emptyTextVerify = ref<string>('');
    let tableVerifyLoading = ref<boolean>(true);
    let paramsVerify = reactive<ObjValueAny>({
        page: 1,
        per_page: 6000,
        coupon_id: +routeParams.id,
        order_by: '',
        sort: '',
    });

    // 排序
    const tableVerifySortChange = ({ order, prop }: TypeTableSort) => {
        const paramsSort: TypeSortParams = getTableSortOrder(order, prop);
        paramsVerify = Object.assign(paramsVerify, paramsSort);
        getVerifyStatsByShop();
    }
    const getVerifyStatsByShop = () => {
        emptyTextVerify.value = '加载中...';
        tableVerifyLoading.value = true;
        postV3CouponVerifyStatsByShop(paramsVerify, { noRepeat: 3 }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                tableDataVerify.value = resp.data;
            } else {
                ElMessage.error(`postV3CouponVerifyStatsByShop：${resp.msg}`);
            }
            tableVerifyLoading.value = false;
            emptyTextVerify.value = '暂无数据';
        })
    }

    // 领用数据明细 ==================================================================================================
    let tableData = ref<ObjValueAny[]>([]);
    let emptyText = ref<string>('');
    let total = ref<number>(0);
    let tableLoading = ref<boolean>(false);
    let params = reactive<ObjValueAny>({
        page: 1,
        per_page: 10,
        keyword: '',
        origin: '',
        status: '',
        order: '',
        sort: '',
    });

    const mdTableSearch = () => {
        handleCurrentChange();
    }
    // 使用状态/结算状态 筛选
    const mdTableSearchStatus = () => {
        if (params.settlement_status === 0 && params.status === '') params.status = 1;
        // 筛选状态未结算且使用状态为 未使用或已失效
        if (params.settlement_status === 0 && (params.status === 0 || params.status === 2)) {
            tableData.value = [];
            return;
        }
        handleCurrentChange();
    }
    // 日期/关键字 搜索
    const mdSearch = (row: FilterTimesRow) => {
        params = Object.assign(params, row);
        handleCurrentChange();
    }
    // 排序
    const tableSortChange = ({ order, prop }: TypeTableSort) => {
        const paramsSort: TypeSortParams = getTableSortOrder(order, prop);
        params = Object.assign(params, paramsSort);
        handleCurrentChange();
    }
    // 选择 每页条数
    const handleSizeChange = (num: number = params.per_page) => {
        params.per_page = num;
        handleCurrentChange();
    }
    // 分页
    const handleCurrentChange = (page: number = 1) => {
        params.page = page;
        getListLoading();
    }
    // 列表请求 loading
    const getListLoading = () => {
        tableLoading.value = true;
        getCouponRecordDetail();
    }
    // 领取明细列表
    // 使用状态
    const statusFilters = reactive<TypeFilters.filter[]>([
        { value: 0, label: baoLiCustom.value ? '未使用' : '已领取' },
        { value: 1, label: '已使用' },
        { value: 2, label: '已失效' },
    ])
    const statusFiltersLabel = reactive<ObjValueStr>(getFiltersDictLabel(statusFilters));
    // 结算状态
    const settlementFilters = reactive<TypeFilters.filter[]>([
        { value: 0, label: '未结算' },
        { value: 1, label: '已结算' },
    ])
    const settlementFiltersLabel = reactive<ObjValueStr>(getFiltersDictLabel(settlementFilters))
    // 领取方式
    const receiveFilters = reactive<TypeFilters.filter[]>([
        { value: '会员领券', label: '商场发券' },
        { value: '会员领券', label: '商场发券' },
    ])

    const getCouponRecordDetail = () => {
        emptyText.value = '加载中...';
        getRestfulMallCouponRecordDetail(+routeParams.id, params, { noRepeat: 1 }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                for (let row of resp.data) {
                    if (row.source) {
                        row.source = `${row.source.substring(0, 3)}*****${row.source.substring(8)}`;
                    }
                }
                tableData.value = resp.data;
                total.value = resp.meta?.total || 0;
            } else {
                ElMessage.error(`getRestfulMallCouponRecordDetail：${resp.msg}`);
            }
            tableLoading.value = false;
            emptyText.value = '暂无数据';
        })
    }

    // 使用店铺
    const shopFilters = ref<ObjValueAny[]>([]);
    const getMallCouponShops = () => {
        getRestfulMallCouponShops(+routeParams.id, {
            per_page: 1000,
            with_mall_shop: 1,
        }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                shopFilters.value = resp.data;
            } else {
                ElMessage.error(`getRestfulMallCouponShops：${resp.msg}`);
            }
        })
    }

    // 更新 详情/领用数据明细=========================================================================================
    const updateDetail = () => {
        getRestfulMallV2CouponDetailHandler(+routeParams.id).then((resp: ObjValueAny) => {
            getDetail(resp);
        })
        getListLoading();
    }
    // 结算/不接算 ==================================================================================================
    let tableDataRow = ref<ObjValueAny>({});
    let settlementDialog = ref<boolean>(false);// 是否显示结算按钮
    let settlementLoading = ref<boolean>(false);// 确认结算 loading
    const showSettlementDialog = (row: ObjValueAny) => {
        settlementDialog.value = true;
        settlementLoading.value = false;
        tableDataRow.value = row;
    }

    const changeSettlement = () => {
        let _type: number = 1;// 结算
        let _message: string = '';// 结算
        if (tableDataRow.value.settlement_status === 1) {
            // 取消结算
            _type = 0;
            _message = '取消'
        }
        ElMessage.closeAll();
        ElMessage({
            showClose: true,
            message: `正在${_message}结算`,
            type: 'success',
            duration: 0,
        });
        settlementLoading.value = true;
        postV3MemberCouponSettlement({
            type: _type,
            id: tableDataRow.value.id
        }).then((resp: ObjValueAny) => {
            cancelSettlementDialog();
            ElMessage.closeAll();
            if (resp.code === 200) {
                ElMessage.success('操作成功');
                updateDetail();
            } else {
                ElMessage.error(resp.msg);
                settlementLoading.value = false;
            }
        }).catch(() => {
            settlementLoading.value = false;
        })
    }
    const cancelSettlementDialog = () => {
        settlementDialog.value = false;
    }

    // 导出 ==================================================================================================
    let ExportModelRef = ref();
    let exportDialogVisible = ref<boolean>(false);
    const exportConfigBody: TypeExport.ConfigBody = {
        keyword: 'member_coupons_data',
        export_mode: 2,
        export_type: 6,
        export_channel: 1,
        coupon_id: +routeParams.id,
    }

    let baoLiCustomExportLoading = ref<boolean>(false);
    let exportSettlementDialog = ref<boolean>(false);
    const exportConfig = reactive<TypeExport.Config>({});
    const showExportModel = () => {
        exportConfig.name = '优惠券领取明细';
        exportConfig.content = { name: detail.value.name };
        if (baoLiCustom.value) {
            exportConfig.body = {
                ...exportConfigBody,
                is_settle: 0,
                match_value: params.keyword,
                status: params.status,
                origin: params.origin,
                shop_id: params.shop_id,
                settlement_status: params.settlement_status,
            }
            if (!params.settlement_status && (params.status === 1 || params.status === '')) {
                const settlementParams: ObjValueAny = JSON.parse(JSON.stringify(params));
                settlementParams.page = 0;
                settlementParams.status = 1;
                settlementParams.settlement_status = 0;
                baoLiCustomExportLoading.value = true;
                getRestfulMallCouponRecordDetail(+routeParams.id, settlementParams).then((resp: ObjValueAny) => {
                    if (resp.code === 200) {
                        if (resp.meta.total > 0 && showSettlementBtn.value) {
                            exportSettlementDialog.value = true;
                        } else {
                            onExport();
                        }
                    } else {
                        ElMessage.error(resp.msg);
                    }
                    baoLiCustomExportLoading.value = false;
                })
            } else {
                onExport();
            }
        } else {
            exportConfig.body = exportConfigBody;
            onExport();
        }
    }
    // 不结算
    const noSettlement = () => {
        exportConfig.body!.is_settle = 0;
        onExport();
    }
    // 结算
    const onSettlement = () => {
        exportConfig.body!.is_settle = 1;
        onExport();
    }
    // 导出领用明细
    const onExport = () => {
        exportSettlementDialog.value = false;
        ExportModelRef.value.exportApi(exportConfig);
    }

    // 导出结算率
    const showSettleExportModel = () => {
        exportConfig.title = '导出结算率';
        exportConfig.name = `结算率-${detail.value.name}`;
        exportConfig.condition = '核销时间';
        exportConfig.content = { name: exportConfig.condition };
        exportConfig.body = {
            keyword: 'member_coupons_data',
            coupon_id: +routeParams.id,
        }
        exportDialogVisible.value = true;
    }
</script>

<style scoped lang="scss">
    .flex1 {
        flex: 1;
    }

    .detail-stats__rate {
        width: 62px;
        display: inline-block;
    }
</style>